import Vue from 'vue'

Vue.filter('formatDate', (value) => {
  if (!value) return ''
  const date = new Date(value)
  return date.toLocaleDateString('zh-CN')
})

Vue.filter('formatDateTime', (value) => {
  if (!value) return ''
  const date = new Date(value)
  return `${date.toLocaleDateString('zh-CN')} ${date.toLocaleTimeString('zh-CN')}`
})

Vue.filter('formatTime', (value) => {
  if (!value) return ''
  const date = new Date(value)
  return date.toLocaleTimeString('zh-CN')
})

Vue.filter('formatSize', (bytes) => {
  if (!bytes) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
})

Vue.filter('truncate', (value, length = 50) => {
  if (!value) return ''
  if (value.length <= length) return value
  return value.substring(0, length) + '...'
})

Vue.filter('capitalize', (value) => {
  if (!value) return ''
  value = value.toString()
  return value.charAt(0).toUpperCase() + value.slice(1)
})

Vue.filter('uppercase', (value) => {
  if (!value) return ''
  return value.toString().toUpperCase()
})

Vue.filter('lowercase', (value) => {
  if (!value) return ''
  return value.toString().toLowerCase()
})